<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
  <template>
    <!-- 巡检计划 -->
    <div class="layout-padding">
      <basic-container class="layout-padding-auto layout-padding-view">
        <avue-crud
          :before-open="handleOpenBefore"
          v-model="form"
          ref="crud"
          :page="page"
          :data="tableData"
          :permission="permissionList"
          :table-loading="tableLoading"
          :option="tableOption"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @row-update="handleUpdate"
          @row-save="handleSave"
          @row-del="rowDel"
          @selection-change="selectionChange"
        >
          <template #menu-left>
            <el-button
              class="filter-item"
              plain
              type="primary"
              icon="el-icon-delete"
              @click="plDelete"
            >
              批量删除
            </el-button>
          </template>
          <template #delFlag='{row}'>
             <el-tag type='success' v-if='row.delFlag==="1"'>启用</el-tag>
             <el-tag type='danger' v-else>停用</el-tag>
          </template>
          <template #obj-form="{ row }">
            <el-tabs v-model="form.planType" type="border-card" @tab-click="handleClick">
              <el-tab-pane label="周期" name="0">
                <el-form-item label="计划起止" required>
                  <el-col :span="11">
                    <el-date-picker
                      value-format="YYYY-MM-DD"
                      :disabled-date="disabledDate"
                      v-model="value1"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      @change="changeDate"
                    >
                    </el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="周期单位" required>
                  <el-col :span="11">
                    <el-radio-group v-model="form.cycleType" @change="changeRadio">
                      <el-radio-button label="0">天</el-radio-button>
                      <el-radio-button label="1">周</el-radio-button>
                    </el-radio-group>
                  </el-col>
                </el-form-item>
                <el-form-item label="执行间隔" required>
                  <el-col :span="11">
                    <span>每</span>
                    <el-input-number
                      v-model="form.frequency"
                      controls-position="right"
                      @change="handleChange"
                      :min="0"
                      :max="maxDays"
                      style="margin: 0 10px"
                    ></el-input-number>
                    <span v-text="form.cycleType == '0' ? '天' : '周'"></span>
                  </el-col>
                </el-form-item>
                <el-form-item label="执行时间" required>
                  <el-col :span="15">
                    <div v-for="(item, i) in form.relList" :key="i" style="margin-bottom: 10px">
                      <el-time-select
                        style="width: 130px; margin-right: 10px"
                        placeholder="开始时间"
                        v-model="item.excuteStartTime"
                        :start="item.start"
                        step="00:30"
                        end="23:59"
                      >
                      </el-time-select>
                      <el-time-select
                        style="width: 130px"
                        placeholder="结束时间"
                        v-model="item.excuteEndTime"
                        start="00:00"
                        step="00:30"
                        end="23:59"
                        :minTime="item.excuteStartTime"
                      >
                      </el-time-select>
                      <span
                        style="color: #409eff; margin-left: 10px; cursor: pointer"
                        @click="addDate"
                        >新增</span
                      >
                      <span
                        style="color: #409eff; margin-left: 10px; cursor: pointer"
                        @click="delDate(item, i)"
                        >删除</span
                      >
                    </div>
                  </el-col>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="自定义" name="1">
                <el-form-item label="执行日期" required>
                  <el-col :span="11">
                    <el-date-picker
                      ref="datesRef"
                      type="dates"
                      v-model="dateArr"
                      :editable="false"
                      placeholder="选择一个或多个日期"
                    >
                    </el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="执行时间" required>
                  <el-col :span="15">
                    <div v-for="(item, i) in form.relList" :key="i" style="margin-bottom: 10px">
                      <el-time-select
                        style="width: 130px; margin-right: 10px"
                        placeholder="开始时间"
                        v-model="item.excuteStartTime"
                        :start="item.start"
                        step="00:30"
                        end="23:59"
                      >
                      </el-time-select>
                      <el-time-select
                        style="width: 130px"
                        placeholder="结束时间"
                        v-model="item.excuteEndTime"
                        start="00:00"
                        step="00:30"
                        end="23:59"
                        :minTime="item.excuteStartTime"
                      >
                      </el-time-select>
                      <span
                        style="color: #409eff; margin-left: 10px; cursor: pointer"
                        @click="addDate"
                        >新增</span
                      >
                      <span
                        style="color: #409eff; margin-left: 10px; cursor: pointer"
                        @click="delDate(item, i)"
                        >删除</span
                      >
                    </div>
                  </el-col>
                </el-form-item>
              </el-tab-pane>
            </el-tabs>
          </template>
        </avue-crud>
      </basic-container>
    </div>
  </template>
  
  <script>
  import { fetchList, getObj, addObj, putObj, delObj, delAllObj } from '/@/api/check/omicheckplan'
  import { getUserById } from '/@/api/om/omworder'
  import { tableOption } from '/@/const/crud/check/omicheckplan'
//   import { mapGetters } from 'vuex'
  
  export default {
    name: 'omicheckplan',
    data() {
      return {
        form: {},
        dateArr: [],
        num: 1,
        radio1: 0,
        value1: [],
        activeName: 'first',
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        selectList: [],
        totalDays: null,
        maxDays: null,
        Formtype: '' //判断弹出窗口是编辑还是新增
        // pickerOptions: {
        //   disabledDate: (date) => {
        //     date.getTime() > Date.now() - 86400000 //通过计算此刻的时间戳限制的只能选择此刻及以前的时间范围
        //   }
        // }
      }
    },
    computed: {
    //   ...mapGetters(['permissions']),
      permissionList() {
        return {
        //   addBtn: this.validData(this.permissions.om_omicheckplan_add, false),
        //   delBtn: this.validData(this.permissions.om_omicheckplan_del, false),
        //   editBtn: this.validData(this.permissions.om_omicheckplan_edit, false)
        }
      }
    },
    watch: {
      'form.checkUserId': {
        handler(val, oldVal) {
          if (val) {
            getUserById(val).then((res) => {
              let list = res.data
              this.form.checkUserName = list?.name
            })
          }
        }
      }
      // 'form.cycleType': {
      //   handler(val, oldVal) {
      //     if (val == 0) {
      //       this.maxDays = this.totalDays
      //     } else {
      //       let totalWeek = Math.floor(this.totalDays / 7)
      //       console.log(totalWeek)
      //       this.maxDays = totalWeek
      //     }
      //   }
      // }
    },
    mounted() {
      //为了解决bug，所以默认值放在了这里
      this.$nextTick(function () {
        // this.dateArr = ["2018-08-03", "2018-08-06"];
      })
    },
    methods: {
      selectionChange(list) {
        this.selectList = list
      },
      // 禁止选择当前日期之前的
      disabledDate(time) {
        return time.getTime() < Date.now() - 8.64e7
      },
      changeRadio(value) {
        if (value == 1) {
          this.form.frequency = null
          let totalWeek = Math.floor(this.totalDays / 7)
          this.maxDays = totalWeek
        } else {
          this.form.frequency = null
          this.maxDays = this.totalDays
        }
      },
      handleChange(value) {},
      handleClick(tab, event) {},
      getList(page, params) {
        this.tableLoading = true
        fetchList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize
            },
            params,
            this.searchForm
          )
        )
          .then((response) => {
            this.tableData = response.data.records
            this.page.total = response.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      rowDel: function (row, index) {
        this.$confirm('是否确认删除ID为' + row.plId, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function () {
            return delObj(row.plId)
          })
          .then((data) => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
          .catch((cancelorerror) => {})
      },
      handleUpdate: function (row, index, done, loading) {
        let arr = []
        for (const iterator of this.dateArr) {
          arr.push(this.newDate(iterator))
        }
        row.planStartTime = this.value1[0] //计划开始时间
        row.planEndTime = this.value1[1] //计划结束时间
        row.excuteDate = arr.toString() //执行日期
  
        //处理其他巡检人员
        let arr2 = row.userRelList
        let obj = {}
        // // 将数组转化为对象
        for (let key in arr2) {
          obj[key] = arr2[key]
        }
        row.userRelList = Object.keys(obj).map((val) => ({
          checkUserId: obj[val]
        }))
  
        putObj(row)
          .then((data) => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      newDate(time) {
        var date = new Date(time)
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        minute = minute < 10 ? '0' + minute : minute
        var s = date.getSeconds()
        s = s < 10 ? '0' + s : s
        return y + '-' + m + '-' + d
      },
      handleSave: function (row, done, loading) {
  
        let arr = []
        for (const iterator of this.dateArr) {
          arr.push(this.newDate(iterator))
        }
        row.planStartTime = this.value1[0] //计划开始时间
        row.planEndTime = this.value1[1] //计划结束时间
        row.excuteDate = arr.toString() //执行日期
        //处理其他巡检人员
        let arr2 = row.userRelList
        let obj = {}
        // // 将数组转化为对象
        for (let key in arr2) {
          obj[key] = arr2[key]
        }
        row.userRelList = Object.keys(obj).map((val) => ({
          checkUserId: obj[val]
        }))
        addObj(row)
          .then((data) => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      currentChange(current) {
        this.page.currentPage = current
      },
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      refreshChange() {
        this.getList(this.page)
      },
      addDate() {
        //新增
        if (this.Formtype == 'add') {
          this.form.relList = []
          this.Formtype = ''
        }
        if (this.form.relList.length == 0) {
          this.form.relList.push({
            excuteEndTime: '23:59',
            start: '00:00',
            id: '',
            excuteStartTime: '00:00'
          })
        } else {
          let start = this.form.relList[this.form.relList.length - 1].excuteEndTime
          this.form.relList.push({
            excuteEndTime: '',
            start: start,
            id: '',
            excuteStartTime: ''
          })
        }
        this.form = { ...this.form } //解决编辑push不更新视图的问题
      },
      delDate(e, x) {
        if (this.form.relList.length == 1) {
          return
        }
        if (this.Formtype == 'edit') {
          if (e.id != '') {
            // this.form.delKeys.push(e.id);
          }
        }
        let middle = this.form.relList
        this.form.relList.splice(x, 1)
        this.form = { ...this.form } //解决编辑push不更新视图的问题
      },
      handleOpenBefore(show, type) {
        if (type == 'add') {
          this.Formtype = 'add'
          this.form.cycleType = '0'
          this.form.planType = '0'
          this.form.frequency = null
          this.maxDays = null
          this.dateArr = []
          this.value1 = []
          this.addDate() //默认有一条数据
        } else {
          this.Formtype = 'edit'
          this.value1 = [this.form.planStartTime, this.form.planEndTime]
          // console.log(this.form,'this.form.excuteDate')
          // this.dateArr = this.form.excuteDate.split(',')
          // 处理其他人员数据
          let arr = []
          this.form.userRelList.forEach((item) => {
            let num = item.checkUserId
            arr.push(num)
          })
          this.form.userRelList = arr
          //处理间隔时间
          if (this.form.cycleType == '0') {
            this.diffDate(this.form.planStartTime, this.form.planEndTime)
            this.maxDays = this.totalDays
          } else if (this.form.cycleType == '1') {
            this.diffDate(this.form.planStartTime, this.form.planEndTime)
            let totalWeek = Math.floor(this.totalDays / 7)
            this.maxDays = totalWeek
          }
          //处理执行时间
          for (var i = 0; i < this.form.relList.length; i++) {
            if (i == 0) {
              this.form.relList[i].start = '00:00'
            } else {
              this.form.relList[i].start = this.form.relList[i - 1].excuteEndTime
            }
          }
        }
        // if (type === 'edit') {
        //   let arr = []
        //   this.form.userRelList.forEach((item) => {
        //     let num = item.checkUserId
        //     arr.push(num)
        //   })
        //   this.form.userRelList = arr
        // }
        show()
      },
      handleUserData(list) {
        let arr = list
        let obj = {}
        // // 将数组转化为对象
        for (let key in arr) {
          obj[key] = arr[key]
        }
        list = Object.keys(obj).map((val) => ({
          checkUserId: obj[val]
        }))
        return list
      },
      changeDate(val) {
        this.diffDate(val[0], val[1])
        this.maxDays = this.totalDays
      },
      diffDate(date1, date2) {
        let myDate_1 = Date.parse(date1)
        let myDate_2 = Date.parse(date2)
        // 将两个日期都转换为毫秒格式，然后做差
        let diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
        this.totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
        return this.totalDays
      },
      //批量删除
      plDelete() {
        if (this.selectList.length > 0) {
          this.$confirm('是否确认删除以选择的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              let ids = []
              this.selectList.forEach((data) => {
                ids.push(data.plId)
              })
              return delAllObj(ids)
            })
            .then((data) => {
              this.$message.success('删除成功')
              this.getList(this.page)
            })
            .catch((cancelorerror) => {})
        }
      }
    }
  }
  </script>
  <style lang="scss" scoped>
  .el-tabs__content {
    .el-form-item {
      margin-top: 20px;
    }
  }
  </style>
  